﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using ServiceManager.Services;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {


            string directoryServerUrl = "192.168.0.105:1618";
            string publishServerUrl = directoryServerUrl;
            DirectoryService.Initialize();
            DirectoryService.SetDirectoryServers(directoryServerUrl, 0, null);
            Common.CodeTimer.Initialize();
            constructMarketInfo();
            loadMarketInfo();
            saveMarketInfo();

            Common.CodeTimer.Time("loadMarketInfo", 10000, loadMarketInfo);

            Common.CodeTimer.Time("saveMarketInfo", 10000, saveMarketInfo);
            Console.Read();
           // testSerialization();
        }



        static string quotSource = "Q01";
        static Quotation.MarketInfo marketInfo;
        private static void constructMarketInfo()
        {
       
            DateTime now = DateTime.Now;
            Quotation.TimeRangeCollection tradingSession = new Quotation.TimeRangeCollection(new List<Quotation.TimeRange>() 
            {
              new Quotation.TimeRange(){ StartTime =Quotation.Time.FromHMM(930),EndTime =Quotation.Time.FromHMM(1130)},
              new Quotation.TimeRange (){StartTime =Quotation.Time.FromHMM(1300),EndTime =Quotation.Time.FromHMM(1500)}
            
            });
            Quotation.TimeRangeCollection chartTimeSlots = new Quotation.TimeRangeCollection(new List<Quotation.TimeRange>() 
            {
              new Quotation.TimeRange(){ StartTime =Quotation.Time.FromHMM(930),EndTime =Quotation.Time.FromHMM(1030)},
              new Quotation.TimeRange(){ StartTime =Quotation.Time.FromHMM(1030),EndTime =Quotation.Time.FromHMM(1130)},
              new Quotation.TimeRange(){ StartTime =Quotation.Time.FromHMM(1300),EndTime =Quotation.Time.FromHMM(1400)},
              new Quotation.TimeRange (){StartTime =Quotation.Time.FromHMM(1400),EndTime =Quotation.Time.FromHMM(1500)}
            
            });

            marketInfo = new Quotation.MarketInfo()
            {
                Status = Quotation.MarketStatus.Closed,
                TradeDay = new Quotation.Date(now),
                MarketTime = new TimeSpan(0, 0, 1),
                UpdateTime = new Quotation.Time(now),
                TradingSession = tradingSession,
                ChartTimeSlots = chartTimeSlots
            };
        
        }

        private static void saveMarketInfo()
        {
            QuotationService.RealtimeQuotation.StockQuotationRepository.UpdateMarketInfo(quotSource, marketInfo);
        }
        private static void loadMarketInfo()
        {
            marketInfo = QuotationService.RealtimeQuotation.StockQuotationRepository.GetMarketInfo(quotSource);
        }


        private static void testSerialization()
        {
            basicInfo = new Quotation.Stock.BasicInfo()
            {
                AccountDate = Quotation.Date.FromYMMDD(20130101),
                AccuredInterest = 0.1,
                AnnualProfit = 0.2,
                BaseStock = "600000",
                BeginDate = Quotation.Date.FromYMMDD(20140303),
                BondBonusDate = Quotation.Date.FromYMMDD(20140303),
                BondConvertRate = 1.2,
                ComponentStockFlag = 'd',
                ConvertQty = 10,
                CurrencyType = "R",
                Decimal = 2,
                DynamicVer = 121212121212,
                EndDate = Quotation.Date.FromYMMDD(20140303),
                EnglishName = "ERE",
                FinancingLoanFlag = 'c',
                FinancingLoanTradingFlag = 'e',
                GuarantyConvertRate = 2.1,
                HighBuyQtyLimit = 100,
                HighSellQtyLimit = 100,
                IndustryType = "S",
                ISINCode = "SDFSDF",
                LastAnnualProfit = 12.0,
                LevelFlag = 'c',
                LowBuyQtyLimit = 1,
                LowSellQtyLimit = 1,
                MarketMakerFlag = 'f',
                MaxOrderPrice = 10.4,
                MinOrderPrice = 6.6,
                OpenPrice = 3.4,
                OrderPriceUnit = 2,
                OtherBizStatus = "asdf",
                ParValue = 3.3,
                PreClosePrice = 3.4,
                PreExchTotalKnockAmt = 234243,
                PreExchTotalKnockQty = 234234,
                QuotationTime = DateTime.Now,
                QuotLevel = Quotation.StockQuotLevel.Level1,
                SecuritiesLoanSellPriceLimitFlag = 'f',
                RepurchaseDay = 4,
                SecuritiesLoanFlag = 'f',
                SecuritiesLoanTradingFlag = 't',
                ShortPrefix = "F",
                StaticVer = 323423432432,
                StkDeliveryDays = 2,
                StkId = new Quotation.SymbolCode("0400000"),
                StkType = Quotation.StockType.ETF基金
            };



            Common.CodeTimer.Initialize();
            Common.CodeTimer.Time("test1", 100000, test1);
            Common.CodeTimer.Time("test2", 100000, test2);
            Console.Read();
        }

        static Quotation.Stock.BasicInfo basicInfo;
        static StockBasicInfo basicInfo2;

        static void test1()
        {
            var bytes = ServiceManager.Utils.StructHelper.ObjectToBytes<Quotation.Stock.BasicInfo>(basicInfo);

        }
        static void test2()
        {
            basicInfo2 = Convert(basicInfo);
            var bytes = ServiceManager.Utils.StructHelper.StructToBytes<StockBasicInfo>(basicInfo2);
        }



        public static StockBasicInfo Convert(Quotation.Stock.BasicInfo basicInfo)
        {
            return new StockBasicInfo()
            {
                AccountDate = basicInfo.AccountDate.ToYMMDD(),
                AccuredInterest = basicInfo.AccuredInterest,
                AnnualProfit = basicInfo.AnnualProfit,
                BaseStock = basicInfo.BaseStock,
                BeginDate = basicInfo.BeginDate.ToYMMDD(),
                BondBonusDate = basicInfo.BondBonusDate.ToYMMDD(),
                BondConvertRate = basicInfo.BondConvertRate,
                ComponentStockFlag = basicInfo.ComponentStockFlag,
                ConvertQty = basicInfo.ConvertQty,
                CurrencyType = basicInfo.CurrencyType,
                Decimal = basicInfo.Decimal,
                DynamicVer = basicInfo.DynamicVer,
                EndDate = basicInfo.EndDate.ToYMMDD(),
                EnglishName = basicInfo.EnglishName,
                FinancingLoanFlag = basicInfo.FinancingLoanFlag,
                FinancingLoanTradingFlag = basicInfo.FinancingLoanTradingFlag,
                GuarantyConvertRate = basicInfo.GuarantyConvertRate,
                HighBuyQtyLimit = basicInfo.HighBuyQtyLimit,
                HighSellQtyLimit = basicInfo.HighSellQtyLimit,
                IndustryType = basicInfo.IndustryType,
                ISINCode = basicInfo.ISINCode,
                LastAnnualProfit = basicInfo.LastAnnualProfit,
                LevelFlag = basicInfo.LevelFlag,
                LowBuyQtyLimit = basicInfo.LowBuyQtyLimit,
                LowSellQtyLimit = basicInfo.LowSellQtyLimit,
                MarketMakerFlag = basicInfo.MarketMakerFlag,
                MaxOrderPrice = basicInfo.MaxOrderPrice,
                MinOrderPrice = basicInfo.MinOrderPrice,
                Name = basicInfo.Name,
                OpenPrice = basicInfo.OpenPrice,
                OrderPriceUnit = basicInfo.OrderPriceUnit,
                OtherBizStatus = basicInfo.OtherBizStatus,
                ParValue = basicInfo.ParValue,
                PreClosePrice = basicInfo.PreClosePrice,
                PreExchTotalKnockAmt = basicInfo.PreExchTotalKnockAmt,
                PreExchTotalKnockQty = basicInfo.PreExchTotalKnockQty,
                QuotationTime = basicInfo.QuotationTime,
                RepurchaseDay = basicInfo.RepurchaseDay,
                SecuritiesLoanFlag = basicInfo.SecuritiesLoanFlag,
                SecuritiesLoanSellPriceLimitFlag = basicInfo.SecuritiesLoanSellPriceLimitFlag,
                SecuritiesLoanTradingFlag = basicInfo.SecuritiesLoanTradingFlag,
                ShortPrefix = basicInfo.ShortPrefix,
                StaticVer = basicInfo.StaticVer,
                StkDeliveryDays = basicInfo.StkDeliveryDays,
                SuspendedFlag = basicInfo.SuspendedFlag,
                Code = basicInfo.StkId.LongCode,
                ExchId = basicInfo.StkId.ExchId,
                TotalCirculatingShare = basicInfo.TotalCirculatingShare,
                TotalIssueQty = basicInfo.TotalIssueQty,
                TradeStageFlag = basicInfo.TradeStageFlag,
                TradeStatus = basicInfo.TradeStatus,
                TradeType = basicInfo.TradeType,
                TradeUnit = basicInfo.TradeUnit,
                Type = basicInfo.StkType,
                UpdateTime = basicInfo.UpdateTime,
                VoteFlag = basicInfo.VoteFlag,
                QuotLevel = basicInfo.QuotLevel

            };
        }



    }


    /// <summary>
    /// 证券基本资料
    /// </summary>
    [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
    internal struct StockBasicInfo
    {
        /// <summary>
        /// 商品代码
        /// </summary>
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MarshalSizeConsts.CodeLength)]
        public string Code;

        /// <summary>
        /// 商品名称
        /// </summary>
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MarshalSizeConsts.NameLength)]
        [ServiceManager.Utils.Encoding("UTF-8")]
        public string Name;

        /// <summary>
        /// 证券简称前缀
        /// </summary>
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5)]
        public string ShortPrefix;

        /// <summary>
        /// 英文简称
        /// </summary>
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 21)]
        public string EnglishName;

        /// <summary>
        /// 基础证券
        /// </summary>
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 7)]
        public string BaseStock;

        /// <summary>
        /// ISIN 编码
        /// </summary>
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 13)]
        public string ISINCode;

        /// <summary>
        /// 商品类别
        /// </summary>
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
        public string Type;

        /// <summary>
        /// 货币种类
        /// </summary>
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 3)]
        public string CurrencyType;

        /// <summary>
        /// 行情来源
        /// </summary>
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MarshalSizeConsts.QuotLevelLength)]
        public string QuotLevel;

        /// <summary>
        /// 行业种类
        /// </summary>
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 40)]
        public string IndustryType;

        /// <summary>
        /// 交易类别
        /// </summary>
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MarshalSizeConsts.TradeTypeLength)]
        public string TradeType;

        /// <summary>
        /// 涨停价
        /// </summary>
        public double MaxOrderPrice;

        /// <summary>
        /// 跌停价
        /// </summary>
        public double MinOrderPrice;

        /// <summary>
        /// 开盘价
        /// </summary>
        public double OpenPrice;

        /// <summary>
        /// 昨收盘价
        /// </summary>
        public double PreClosePrice;

        /// <summary>
        /// 上市日期
        /// </summary>
        public Int32 BeginDate;

        /// <summary>
        /// 到期/交割日
        /// </summary>
        public Int32 EndDate;

        /// <summary>
        /// 退市日期
        /// </summary>
        public Int32 AccountDate;


        /// <summary>
        /// 价格档位
        /// </summary>
        public double OrderPriceUnit;

        /// <summary>
        /// 小数位数
        /// </summary>
        public Int32 Decimal;

        /// <summary>
        /// 交易单位
        /// </summary>
        public Int32 TradeUnit;

        /// <summary>
        /// 买入下限
        /// </summary>
        public Int32 LowBuyQtyLimit;

        /// <summary>
        /// 卖出下限
        /// </summary>
        public Int32 LowSellQtyLimit;

        /// <summary>
        /// 买入上限
        /// </summary>
        public Int32 HighBuyQtyLimit;

        /// <summary>
        /// 卖出上限
        /// </summary>
        public Int32 HighSellQtyLimit;

        /// <summary>
        /// 每股面值
        /// </summary>
        public double ParValue;

        /// <summary>
        /// 总发行量
        /// </summary>
        public Int64 TotalIssueQty;

        /// <summary>
        /// 流通股数
        /// </summary>
        public Int64 TotalCirculatingShare;

        /// <summary>
        /// 每百元应计利息
        /// </summary>
        public double AccuredInterest;

        /// <summary>
        /// 昨日成交量
        /// </summary>
        public Int64 PreExchTotalKnockQty;

        /// <summary>
        /// 昨日成交金额
        /// </summary>
        public double PreExchTotalKnockAmt;

        /// <summary>
        /// 每手数量
        /// </summary>
        public Int32 ConvertQty;

        /// <summary>
        /// 市场
        /// </summary>
        public char ExchId;

        /// <summary>
        /// 交易状态
        /// </summary>
        public char TradeStatus;

        /// <summary>
        /// 交收天数
        /// </summary>
        public Int16 StkDeliveryDays;

        /// <summary>
        /// 停盘标志
        /// </summary>
        public char SuspendedFlag;

        /// <summary>
        /// 上年每股利润
        /// </summary>
        public double LastAnnualProfit;

        /// <summary>
        /// 本年每股利润
        /// </summary>
        public double AnnualProfit;

        /// <summary>
        /// 债券起息日
        /// </summary>
        public Int32 BondBonusDate;

        /// <summary>
        /// 债券折合比例
        /// </summary>
        public double BondConvertRate;

        /// <summary>
        /// 担保物折算率
        /// </summary>
        public double GuarantyConvertRate;

        /// <summary>
        /// 融资标的标志
        /// </summary>
        public char FinancingLoanFlag;

        /// <summary>
        /// 融券标的标志
        /// </summary>
        public char SecuritiesLoanFlag;

        /// <summary>
        /// 成份股标志
        /// </summary>
        public char ComponentStockFlag;

        /// <summary>
        /// 做市商标志
        /// </summary>
        public char MarketMakerFlag;

        /// <summary>
        /// 证券级别
        /// </summary>
        public char LevelFlag;

        /// <summary>
        /// 产品交易阶段
        /// </summary>
        public char TradeStageFlag;

        /// <summary>
        /// 融资交易状态
        /// </summary>
        public char FinancingLoanTradingFlag;

        /// <summary>
        /// 融券交易状态
        /// </summary>
        public char SecuritiesLoanTradingFlag;

        /// <summary>
        /// 融券卖出价格限制
        /// </summary>
        public char SecuritiesLoanSellPriceLimitFlag;

        /// <summary>
        /// 网络投票标志
        /// </summary>
        public char VoteFlag;

        /// <summary>
        /// 其他业务状态
        /// </summary>
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
        public string OtherBizStatus;


        /// <summary>
        /// 回购天数
        /// </summary>
        public int RepurchaseDay;


        /// <summary>
        /// 静态资料版本，格式为：YYYYMMDDxxxxxx，即：年月日+递增数字
        /// </summary>
        public Int64 StaticVer;

        /// <summary>
        /// 动态资料版本，格式为：YYYYMMDDxxxxxx，即：年月日+递增数字
        /// </summary>
        public Int64 DynamicVer;

        /// <summary>
        ///记录更新的时间
        /// </summary>
        public DateTime UpdateTime;

        /// <summary>
        /// 行情记录中包含的行情时间
        /// </summary>
        public DateTime QuotationTime;
    }
    public class MarshalSizeConsts
    {
        public const int CodeLength = 20;
        public const int NameLength = 30;
        public const int AuthCodeLength = 21;
        public const int FutureProductIdLength = 9;

        public const int QuotLevelLength = 4;
        public const int StkTypeLength = 4;
        public const int TradeTypeLength = 4;
        public const int BSTypeLength = 4;
    }
}
